﻿#region License Information (GPL v2)
/*
    Source Queries - Source Server Queries
    Copyright (C) 2009  Source Queries Developers

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
    
    Optionally you can also view the license at <http://www.gnu.org/licenses/>.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace SourceQueries
{
    public partial class TestForm : Form
    {
        private Source source = new Source();
        private string lastInput = string.Empty;

        public TestForm()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] info = GetServerInfo();
            if (info != null)
            {
                source.ConnectionStatus += new Source.StringEventHandler(source_ConnectionStatus);
                source.ServerOutput += new Source.StringEventHandler(source_ServerOutput);
                source.Connect(info[0], info[1]);
            }

            source.LogOutput += new Source.LogEventHandler(source_LogOutput);
            source.ListenLogs(7130);
        }

        private string[] GetServerInfo()
        {
            // info = server.txt = "ip:port,password"
            string info = File.ReadAllLines(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "server.txt"), Encoding.UTF8)[0];
            string[] split = info.Split(',');
            if (split.Length == 2)
            {
                return split;
            }

            return null;
        }

        private void source_LogOutput(LogPacket packet)
        {
            ConsoleWriteLine(packet.Log, 1);
            if (packet.Chat != null)
            {
                Color color = Color.White;
                if (packet.Team == "Red")
                {
                    color = Color.FromArgb(255, 150, 150);
                }
                else if (packet.Team == "Blue")
                {
                    color = Color.FromArgb(0, 200, 255);
                }
                else if (packet.Team == "Spectator")
                {
                    color = Color.WhiteSmoke;
                }

                ListViewItem lvi = new ListViewItem(packet.Time.ToLongTimeString());
                lvi.SubItems.Add(packet.Nick);
                lvi.SubItems.Add(packet.Chat.MessageType);
                lvi.SubItems.Add(packet.Chat.Message);
                lvi.BackColor = color;
                lvi.Tag = packet;
                lvChatLogs.Items.Add(lvi);
                if (cbAutoScroll.Checked)
                {
                    lvChatLogs.Items[lvChatLogs.Items.Count - 1].EnsureVisible();
                }
            }
        }

        private void source_ServerOutput(string value)
        {
            this.BeginInvoke(new MethodInvoker(delegate()
                {
                    ConsoleWriteLine(value.Trim(), 0);
                }));
        }

        private void source_ConnectionStatus(string value)
        {
            this.BeginInvoke(new MethodInvoker(delegate()
                {
                    ConsoleWriteLine(value, 0);
                }));
        }

        private void ConsoleWriteLine(string text, int type)
        {
            text = text.Replace("\n", "\r\n");
            if (type == 0) // Console output
            {
                txtConsole.AppendText(text + "\r\n");
            }
            else if (type == 1) // Log output
            {
                Color color;
                if (lvLogs.Items.Count % 2 == 0)
                {
                    color = Color.White;
                }
                else
                {
                    color = Color.WhiteSmoke;
                }

                lvLogs.Items.Add(text).BackColor = color;
                if (cbAutoScroll.Checked)
                {
                    lvLogs.Items[lvLogs.Items.Count - 1].EnsureVisible();
                }
            }
        }

        private void txtInput_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                lastInput = txtInput.Text;
                ConsoleWriteLine("> " + lastInput, 0);
                string command = txtInput.Text;
                if (tcTabs.SelectedTab.Text == "Chat Logs")
                {
                    command = "say " + command;
                }

                source.SendCommand(command);
                txtInput.ResetText();
                e.SuppressKeyPress = true;
            }
            else if (e.KeyCode == Keys.Up)
            {
                e.Handled = true;
                txtInput.Text = lastInput;
                txtInput.SelectionStart = txtInput.TextLength;
            }
        }

        private void tsmiLogsCopy_Click(object sender, EventArgs e)
        {
            if (lvLogs.SelectedItems.Count > 0)
            {
                string clipboard = "";
                foreach (ListViewItem lvi in lvLogs.SelectedItems)
                {
                    clipboard += lvi.Text;
                }

                if (!string.IsNullOrEmpty(clipboard))
                {
                    Clipboard.SetText(clipboard);
                }
            }
        }

        private void tsmiChatLogsCopy_Click(object sender, EventArgs e)
        {
            if (lvChatLogs.SelectedItems.Count > 0)
            {
                List<string> clipboardList = new List<string>();
                foreach (ListViewItem lvi in lvChatLogs.SelectedItems)
                {
                    LogPacket packet = (LogPacket)lvi.Tag;
                    clipboardList.Add(string.Format("{0} - {1} ({2}): {3}", packet.Time.ToLongTimeString(), packet.Nick,
                        packet.Chat.MessageType, packet.Chat.Message));
                }

                string clipboard = string.Join("\r\n", clipboardList.ToArray());
                if (!string.IsNullOrEmpty(clipboard))
                {
                    Clipboard.SetText(clipboard);
                }
            }
        }

        private void TestForm_Resize(object sender, EventArgs e)
        {
            this.Refresh();
        }

        private void TestForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            source.Dispose();
        }
    }
}